#pragma once
#include<vector>
#include<string>
#include<algorithm>
//实现异步缓冲区中的任务写入缓冲区
namespace logs
{
    #define DEFAULT_BUFFER_SIZE (1*1024)//缓冲区大小默认为1kb
    #define THRESHOLD_BUFFER_SIZE (4*1024)//阈值默认为4kb
    #define INCREASE_BUFFER_SIZE (1*1024)//超过阈值后每次增长1kb
    class buffer
    {
    public:
        buffer()
        :_buffer((DEFAULT_BUFFER_SIZE))
        {
            ;
        }
        //往缓冲区push数据
        void push(const char* dst,size_t len)
        {
            EnSureEnoughsize(len);
            std::copy(dst,dst+len,&_buffer[_writer_index]);
            movewriter(len);
        }
        size_t ReadAbleSize()
        {    
            return _writer_index - _reader_index; 
        }
        size_t WriteAbleSize()
        {    
            return _buffer.size() - _writer_index; 
        }
        //返回可读位置的起始地址
        const char* begin()
        {
            return &_buffer[_reader_index];
        }
        bool empty()
        {
            return _reader_index == _writer_index;
        }
        void movewriter(size_t len)
        {
            _writer_index += len;
        }
        void moveReader(size_t len)
        {
            _reader_index += len;
        }
        //重置归零
        void reset()
        {
            _reader_index = 0;
            _writer_index = 0;
        }
        void swap(logs::buffer& buf)
        {
            std::swap(_buffer,buf._buffer);
            std::swap(_writer_index,buf._writer_index);
            std::swap(_reader_index,buf._reader_index);
        }
    // private:
        void EnSureEnoughsize(size_t len)//保证扩容后可以容纳len个字符
        {
            if(_buffer.size() - _writer_index >= len)
                return;
            int newsize = 0;
            while(_buffer.size() - _writer_index < len)
            {
                if(_buffer.size() < THRESHOLD_BUFFER_SIZE)//缓冲区大小小于阈值,size增长为翻倍
                    newsize = _buffer.size()*2;
                else
                    newsize = _buffer.size() +  INCREASE_BUFFER_SIZE;
                _buffer.resize(newsize);    //扩容   
            }    
        }
        std::vector<char> _buffer;
        int _writer_index = 0;
        int _reader_index = 0;    
    };
};